import { useEffect, useRef, useState } from "react";
import { TabsType, TypeValueProps } from "./type";
import styles from "./index.modules.less";
import {
  getMySaleCardList,
  getRelatedSaleCardList,
  getSaleCardList,
} from "@/services/sale";
import { Card, Col, Empty, message, Row, Spin, Tag } from "antd";
import { history } from "@umijs/max";
import { gutter } from "../const/keys";
import { sleep } from "@/utils";

type Props = {
  type: TabsType;
  params: any;
  projectStage: {
    label: string;
    value: TypeValueProps;
  };
};
const App = (props: Props) => {
  const { type, projectStage, params } = props;
  //lock
  const lockRef = useRef(false);
  const zhanweiRef = useRef<HTMLDivElement>(null);
  const wrapRef = useRef<HTMLDivElement>(null);
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize] = useState<number>(5);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const handleScroll = () => {
    if (wrapRef.current && zhanweiRef.current) {
      const wrapRect = wrapRef.current.getBoundingClientRect();
      const zhanweiRect = zhanweiRef.current.getBoundingClientRect();
      if (zhanweiRect.top <= wrapRect.bottom && !lockRef.current) {
        setPageNum(pageNum + 1);
      }
    }
  };

  useEffect(() => {
    setPageNum(1);
  }, []);
  useEffect(() => {
    if (lockRef.current) {
      console.log("没有更多数据了");
      return;
    }

    (async () => {
      let result: any;
      const query = {
        ...params,
        pageNum,
        pageSize,
        projectStage: projectStage.value,
      };
      delete query.current;
      delete query.activeKey;
      setLoading(true);
      await sleep(500);
      switch (type) {
        case "ALL":
          result = await getSaleCardList(query);
          break;
        case "MY":
          result = await getMySaleCardList(query);
          break;
        case "FOLLOW":
          result = await getRelatedSaleCardList(query);
          break;
      }
      const { data = [], msg, success } = result || {};
      if (!success) {
        message.error(msg || "获取数据失败");
      }
      if (success) {
        const list = [...(dataSource || [])];
        if (data.length < pageSize) {
          //说明没有更多数据了
          lockRef.current = true;
        } else {
          lockRef.current = false;
        }
        data.forEach((item: any) => {
          list.push(item);
        });
        setDataSource(list);
      }
      setLoading(false);
    })();
  }, [type, projectStage, pageNum, pageSize]);

  return (
    <Card title={`${projectStage.label}(${dataSource?.length}) `} size="small">
      <div
        className={styles.cardItem}
        ref={wrapRef}
        onScroll={() => {
          handleScroll();
        }}
      >
        <Spin spinning={loading}>
          {dataSource?.length === 0 ? <Empty /> : null}
          <Row gutter={[gutter, 10]}>
            {dataSource?.map((item) => {
              return (
                <Col span={24} key={item.id}>
                  <div
                    className={styles.cardListItem}
                    onClick={() => {
                      history.push(`/sale/detail/${item.id}`);
                    }}
                  >
                    <Row gutter={[gutter, gutter]}>
                      <Col span={24}>
                        <strong>{item.opportunityName}</strong>
                      </Col>
                      <Col span={24}>
                        <Row justify="space-between">
                          <Col style={{ fontSize: 12 }}>
                            ¥
                            {(
                              (item.estimatedContractAmount || 0) / 100
                            ).toFixed(2)}
                          </Col>
                          <Col style={{ fontSize: 12 }}>
                            成单概率&nbsp;
                            <Tag color="orange" style={{ fontSize: 12 }}>
                              {item.transactionProbability}%
                            </Tag>
                          </Col>
                        </Row>
                      </Col>
                    </Row>
                  </div>
                </Col>
              );
            })}
          </Row>
          <div ref={zhanweiRef} className={styles.zhanwei}>
            &nbsp;
          </div>
        </Spin>
      </div>
    </Card>
  );
};
export default App;
